package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.Voice;
import com.tanhua.dubbo.api.mongo.PeachblossomApi;
import com.tanhua.dubbo.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service(timeout = 200000)
public class PeachblossomApiImpl implements PeachblossomApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    /**
     * 保存语音消息
     *
     * @param voice
     */
    @Override
    public void saveVoice(Voice voice) {
        Long vid = idService.getNextId("voice");
        voice.setVid(vid.intValue());
        mongoTemplate.save(voice);
    }

    /**
     * 返回近7天内的语音数据
     *
     * @return
     */
    @Override
    public List<Voice> find(Long uid) {
        Query query = new Query(Criteria.where("state").is(0).
                and("created").gte(System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000).and("userId").ne(uid));
        List<Voice> voiceList = mongoTemplate.find(query, Voice.class);
        return voiceList;
    }

    /**
     * 将语音数据的状态修改为1
     *
     * @param voice
     */
    @Override
    public void update(Voice voice) {
        Query query = new Query(Criteria.where("vid").is(voice.getVid()));
        Update update = new Update().set("state",voice.getState());
        mongoTemplate.updateFirst(query, update, Voice.class);
    }
}
